<?php
/**
 * Db Model
 *
 * @author      hyperjiang <hyperjiang@gmail.com>
 * @copyright   Copyright (c) 2008 (http://www.imeelee.com)
 * @license     http://www.gnu.org/licenses/gpl.html     GPL 3
 */
class DbModel extends Ext_Model_Abstract
{

    /**
     * 构造方法
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取数据查询的 SQL
     *
     * @return EGP_Db_Select
     */
    public function listSql()
    {
        return $this->db->select()->from('user');
    }

    /**
     * 插入数据
     *
     * @param  array  $post
     */
    public function insert(array $post)
    {
        $validator = $this->_validate($post);
        if (!$validator->isValid()) {
            throw new EGP_Exception($validator->getMessage());
        }

        $data = array(
            'username' => $post['username'],
            'nickname' => $post['nickname'],
            'homepage' => $post['homepage'],
        );
        $this->db->insert('user', $data);
        return $this->db->lastInsertId();
    }

    /**
     * 对数据进行校验
     *
     * @param  array  $data
     * @return EGP_Validator
     */
    protected function _validate(array $data)
    {
        $validator = new EGP_Validator();
        return $validator->check(
                $data['username'],
                array(
                    array('NotEmpty', 'username 不允许为空'),
                    array('English', 'username 包含除 [a-zA-Z0-9_] 之外的非法字符'),
                    array('StringLength' => array(6, 50), 'username 必须介于 6~50 个字符之间'),
                )
            )
            ->check(
                $data['homepage'],
                array(
                    array('NotEmpty', 'homepage 不允许为空'),
                    array('StringLength' => array(0, 200), 'homepage 必须小于 200 个字符'),
                    array('Url', 'homepage 不是有效的 URL 地址'),
                )
            );
    }

}